<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="笔记标题" prop="noteTitle">
        <el-input
          v-model="queryParams.noteTitle"
          placeholder="请输入笔记标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['know:notes:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['know:notes:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['know:notes:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="notesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="80">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属用户" align="center" prop="sysUser.nickName" />
      <el-table-column label="笔记标题" align="center" prop="noteTitle" />
        <el-table-column label="是否公开" align="center" prop="isVisibility" :formatter="formatYesNo" />
      <el-table-column label="是否有附件" align="center" prop="attachUrl" :formatter="formatYesNo" />
      <el-table-column label="点赞人数" align="center" prop="likeNum" />
      <el-table-column label="收藏人数" align="center" prop="favoritesNum" @click="showFavoritesDialog" />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['know:notes:edit']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['know:notes:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-chat-dot-round"
            @click="showCommentDialog(scope.row)"
          >查看评论</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-chat-dot-round"
            @click="showFavoritesDialog(scope.row)"
          >收藏人数</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 收藏列表弹窗 -->
    <el-dialog
      title="收藏列表"
      :visible.sync="favoritesDialogVisible"
      width="800px"
      append-to-body
    >
      <el-table v-loading="favoritesLoading" :data="favoritesList">
        <el-table-column label="序号" align="center" width="80">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收藏人" align="center" prop="userName" />
        <el-table-column label="收藏时间" align="center" prop="createAt">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="favoritesTotal > 0"
        :total="favoritesTotal"
        :page.sync="favoritesQueryParams.pageNum"
        :limit.sync="favoritesQueryParams.pageSize"
        @pagination="getFavoritesList"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="favoritesDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
    <!-- 评论查看弹窗 -->
    <el-dialog
      title="评论详情"
      :visible.sync="commentDialogVisible"
      width="800px"
      append-to-body>
      <div v-loading="commentLoading">
        <!-- 使用之前实现的评论组件 -->
        <comment-list :comments="commentTree" :post-id="pkId" :commentType="2" @refresh-comments="loadComments" />
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="commentDialogVisible = false">关 闭</el-button>
  </span>
    </el-dialog>
    <!-- 添加或修改笔记对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <DialogPage :fileData="previewData" :show="previewPageOpen" @closeDialog="closePreview" :title="previewData.fileName" width="60%" />
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="笔记标题" prop="noteTitle">
          <el-input v-model="form.noteTitle" placeholder="请输入笔记标题" :disabled="!isAdd" />
        </el-form-item>
        <el-form-item label="笔记内容">
          <editor v-model="form.noteContent" :min-height="192"  :disabled="!isAdd" />
        </el-form-item>
        <el-form-item label="是否公开" prop="isVisibility">
          <el-switch
            v-model="form.isVisibility"
            active-value="1"
            inactive-value="0"
            active-text="是"
            inactive-text="否"
            :disabled="!isAdd"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="附件">
<!--          <el-button size="small" type="primary" @click="openUploadDialog('pdf')" :disabled="!isAdd">点击上传文件</el-button>-->
          <div class="uploadBox">
            <el-upload
              :disabled="!isAdd"
              class="upload-demo"
              action="/dev-api/common/upload"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              :file-list="uploadFileList"
              :append-to-body="true"
            >
              <el-button size="small" type="primary" @click="openUploadDialog('pdf')" :disabled="!isAdd">点击上传文件</el-button>
            </el-upload>
            <!-- 添加预览按钮 -->
            <el-button v-if="form.attachUrl" class="buttonStyle" size="small" type="info" @click="previewFile('practice')">预览</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="!isAdd">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 上传文件弹窗 -->
<!--    <el-dialog :title="'上传附件'" :visible.sync="uploadDialogVisible" width="500px">-->
<!--      <el-upload-->
<!--        class="upload-demo"-->
<!--        action="/dev-api/common/upload"-->
<!--        :on-success="handleUploadSuccess"-->
<!--        :on-error="handleUploadError"-->
<!--        :before-upload="beforeUpload"-->
<!--        :file-list="uploadFileList"-->
<!--        :append-to-body="true"-->
<!--        :z-index="9999"-->
<!--      >-->
<!--        <el-button size="small" type="primary">点击上传</el-button>-->
<!--      </el-upload>-->
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button @click="uploadDialogVisible = false">关闭</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->
  </div>
</template>

<script>
import { listNotes, getNotes, delNotes, addNotes, updateNotes } from "@/api/know/notes";
import CommentList from "@/components/Comment/CommentList.vue";
import {commentTree} from "@/api/know/comments";
import DialogPage from "@/views/know/preview/DialogPage.vue";
import {listFavorites} from "@/api/know/favorites";

export default {
  name: "Notes",
  components: {DialogPage, CommentList},
  props: {
    knowledgePointId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      //  用于定义预览信息
      previewData:{

      },
      previewPageOpen: false,
      // 显示搜索条件
      showSearch: true,
      uploadDialogVisible: false,
      uploadFileList:[],
      favoritesDialogVisible: false, // 收藏列表弹窗显示状态
      favoritesLoading: false, // 收藏列表加载状态
      favoritesList: [], // 收藏列表数据
      favoritesTotal: 0, // 收藏列表总条数
      favoritesQueryParams: {
        pageNum: 1,
        pageSize: 10,
        noteId: null
      },
      // 总条数
      total: 0,
      // 笔记表格数据
      notesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        noteTitle: null,
        knowledgePointId: this.knowledgePointId // 使用传入的知识点 ID
      },
      // 表单参数
      form: {},
      commentDialogVisible: false,  // 评论弹窗显示状态
      currentPost: null,            // 当前查看的帖子
      commentTree: [],              // 评论树数据
      commentLoading: false,         // 评论加载状态
      pkId:"",
      // 表单校验
      rules: {
        isVisibility: [
          { required: true, message: "是否公开：0否 1是不能为空", trigger: "blur" }
        ],
      },
      isAdd: false // 标记是否可编辑
    };
  },
  created() {
    if (this.knowledgePointId) {
      this.queryParams.knowledgePointId = this.knowledgePointId;
    }
    this.getList();
  },
  watch: {
    knowledgePointId(newId) {
      this.queryParams.knowledgePointId = newId;
      this.getList(); // 当 ID 变化时重新获取数据
    }
  },
  methods: {
    showFavoritesDialog(row) {
      this.favoritesQueryParams.noteId = row.noteId;
      this.favoritesQueryParams.pageNum = 1; // 重置页码
      this.favoritesDialogVisible = true;
      this.getFavoritesList();
    },
    getFavoritesList() {
      this.favoritesLoading = true;
      listFavorites(this.favoritesQueryParams).then(response => {
        this.favoritesList = response.rows;
        this.favoritesTotal = response.total;
        this.favoritesLoading = false;
      }).catch(error => {
        console.error('获取收藏列表失败:', error);
        this.$message.error('收藏列表加载失败');
        this.favoritesLoading = false;
      });
    },
    previewFile(fileExtension) {
      let previewUrl = '';
      let preViewType = '';
      console.log("form =>",this.form);
      switch (fileExtension){
        case 'pdf':
          preViewType = 'pdf';
          previewUrl = this.form.attachUrl;
          this.previewData.type = preViewType;
          this.previewData.url = previewUrl;
          break;
        case 'excel':
          preViewType = 'excel';
          previewUrl = this.form.attachUrl;
          this.previewData.type = preViewType;
          this.previewData.url = previewUrl;
          break;
        case 'practice':
        case 'docx':
          preViewType = 'word';
          previewUrl = this.form.attachUrl;
          this.previewData.type = preViewType;
          this.previewData.url = previewUrl;
          console.log('this.previewData =>',this.previewData)
          break;
        case 'video':
          preViewType = 'video';
          previewUrl = this.form.attachUrl;
          this.previewData.type = preViewType;
          this.previewData.url = previewUrl;
          break;
        default:
          this.$message.warning('暂不支持该文件格式的预览');
          return;
      }
      //  统一处理文件名称
      this.previewData.fileName = this.getFileName(previewUrl)
      this.previewPageOpen = true;
    },
    openUploadDialog(type) {
      this.currentUploadType = type;
      // this.uploadDialogVisible = true;
    },
    handleUploadSuccess(response, file, fileList) {
      console.log(`${this.currentUploadType} 文件上传成功`, response);
      if (this.currentUploadType === 'pdf') {
        this.form.pptUrl = response.url;
      } else if (this.currentUploadType === 'excel') {
        this.form.videoUrl = response.url;
      } else if (this.currentUploadType === 'practice') {
        this.form.practiceUrl = response.url;
      }
    },
    handleUploadError(err, file, fileList) {
      console.error(`${this.currentUploadType} 文件上传失败`, err);
    },
    beforeUpload(file) {
      // 上传前的校验逻辑，比如文件类型、大小等
      const isAllowedType = true; // 根据实际需求修改
      const isAllowedSize = true; // 根据实际需求修改
      if (!isAllowedType) {
        this.$message.error('不支持的文件类型');
      }
      if (!isAllowedSize) {
        this.$message.error('文件大小超出限制');
      }
      return isAllowedType && isAllowedSize;
    },
    closePreview(){
      this.previewPageOpen = false;
    },
    getFileName(name) {
      if (name) {
        let resName = '';
        const parts = name.split('/');
        if (parts.length > 1) {
          resName = parts[parts.length - 1]
          if (resName.indexOf('.') > -1) {
            resName = resName.substring(0, resName.lastIndexOf('.'));
          }
          return resName;
        }
      }
      return name;
    },
    // 显示评论弹窗
    async showCommentDialog(row) {
      this.currentPost = row;
      this.commentDialogVisible = true
      this.pkId = row.knowledgePointId
      try {
        this.commentLoading = true
        commentTree({infoId:row.knowledgePointId,commentType:2}).then(response => {
          this.commentTree  = response.data
          this.loading = false;
        });
      } catch (e) {
        console.error('获取评论失败:', e)
        this.$message.error('评论加载失败')
      } finally {
        this.commentLoading = false
      }
    },
    loadComments(){
      commentTree({infoId:this.pkId,commentType:2}).then(response => {
        this.commentTree  = response.data
        this.loading = false;
      });
    },
    formatYesNo(row, column, cellValue) {
      return cellValue === "" || cellValue==null || cellValue===0  ? '否' : '是';
    },
    /** 查询笔记列表 */
    getList() {
      console.log(this.queryParams)
      this.loading = true;
      listNotes(this.queryParams).then(response => {
        this.notesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        noteId: null,
        knowledgePointId: null,
        userId: null,
        noteTitle: null,
        noteContent: null,
        isVisibility: null,
        attachUrl: null,
        isValid: null,
        createdBy: null,
        createdAt: null,
        updateBy: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.noteId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加笔记";
      this.isAdd = true; // 标记为新增操作
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const noteId = row.noteId || this.ids
      getNotes(noteId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改笔记";
        this.isAdd = false; // 标记为详情操作
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.noteId != null) {
            updateNotes(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.knowledgePointId = this.knowledgePointId;
            addNotes(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const noteIds = row.noteId || this.ids;
      this.$modal.confirm('是否确认删除笔记编号为"' + noteIds + '"的数据项？').then(function() {
        return delNotes(noteIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('know/notes/export', {
        ...this.queryParams
      }, `notes_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
  .uploadBox{
    display: flex;
    gap: 10px;
  }
  .buttonStyle{
    height: 36px;
  }
</style>
